/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.facebook.fresco.helper.config;

import ohos.app.IAbilityManager;

import com.facebook.common.internal.Supplier;
import com.facebook.common.util.ByteConstants;
import com.facebook.fresco.helper.utils.MLog;
import com.facebook.imagepipeline.cache.MemoryCacheParams;

import java.util.Locale;

/**
 * 内存缓存配置
 *
 * @since 2021-07-29
 */
public class BitmapMemoryCacheParamsSupplier implements Supplier<MemoryCacheParams> {
    private final IAbilityManager mIAbilityManager;

    /**
     * 位图内存缓存参数供应商
     *
     * @param mIAbilityManager 米数量经理
     */
    public BitmapMemoryCacheParamsSupplier(IAbilityManager mIAbilityManager) {
        this.mIAbilityManager = mIAbilityManager;
    }

    @Override
    public MemoryCacheParams get() {
        return new MemoryCacheParams(
            getMaxCacheSize(),
            256, // MAX_CACHE_ENTRIES
            Integer.MAX_VALUE, // MAX_EVICTION_QUEUE_SIZE
            Integer.MAX_VALUE, // MAX_EVICTION_QUEUE_ENTRIES
            Integer.MAX_VALUE); // MAX_CACHE_ENTRY_SIZE
    }

    private int getMaxCacheSize() {
        final int maxMemory = Math.min(mIAbilityManager.getAppMemory() * ByteConstants.MB, Integer.MAX_VALUE);
        MLog.info(String.format(Locale.getDefault(), "Fresco Max memory [%d] MB", (maxMemory / ByteConstants.MB)));
        if (maxMemory < 32 * ByteConstants.MB) {
            return 4 * ByteConstants.MB;
        } else if (maxMemory < 64 * ByteConstants.MB) {
            return 6 * ByteConstants.MB;
        } else {
            // We don't want to use more ashmem on Gingerbread for now, since it doesn't respond well to
            // native memory pressure (doesn't throw exceptions, crashes app, crashes phone)
            return maxMemory / 4;
        }
    }
}
